package com.zt.bigdata.spark.scala.chapter8

import java.io.{File, FileInputStream}

import org.slf4j.LoggerFactory

/**
  *
  */

trait Log {
  protected lazy val logger = LoggerFactory.getLogger(this.getClass)

  def send(): Unit = {
    logger.info("发送异常到MQ")
  }
}

case class Person(val name: String, val age: Option[Int]) {
  require(age.get > 0, "age less than 0 is not allowed")

  def this(name: String) =
    this(name, Some(18))


  def this(name: String, age: Int) = this(name, Some(age))

  override def toString: String = s"name=$name,age=$age"
}

abstract class BulkReader[T](val source: T) extends Log {
  def read: String
}

//                                                         父类构造器
class StringReader(override val source: String) extends BulkReader(source) {
  override def read: String = source
}

class FileReader(override val source: File, private val BUF_SIZE: Int = 0x400) extends BulkReader(source) {

  def read: String = {
    val builder: StringBuilder = new StringBuilder
    var inputStream: FileInputStream = null
    try {
      inputStream = new FileInputStream(source)
      val bytes = new Array[Byte](BUF_SIZE)
      var reading = true
      while (reading) {
        inputStream.read(bytes) match {
          case -1 => reading = false
          case len => builder.++=(new String(bytes, 0, len))
        }
      }
    } catch {
      case e: Throwable => logger.error(s"异常: ${e.getMessage} ")
    } finally {
      if (null != inputStream) {
        inputStream.close()
      }
    }
    builder.result
  }

}

object Main extends App {
  var reader = new FileReader(new File("/Users/zhangtong/IdeaProjects/hangy/zhangtong/springcloud/allin/spark/spark-project/src/main/scala/com/zt/bigdata/spark/package-info.java"))
  println(reader.read)

  reader = new FileReader(new File(""))
  println(reader.read)


  val stringReader = new StringReader("hello")
  println(stringReader.read)
  stringReader.send() //特质混入

  val person = Person("zhang", Some(18)) //调用伴生对象的apply方法  不用new生成
  println(person)
  val person2 = new Person("zhang") //调用构造函数 需要new def this(name: String) = this(name, Some(18))

  println(new Person(null, 1))
  new Person("zhang")
}
